<template>
	<view class="content pageBg">
		<nav-bar :header="userInfo.avatar" :score="userInfo.score" :usertype="usertype" :level="level"
			@addScoreClick="addScoreClick" @userInfoClick="userInfoClick" @rankClick="rankClick"></nav-bar>
		<view class="suggest" @click="suggestClick">
			<image class="coin" v-if="appKey.isJump && usertype != 1" :src="appKey.toolimageURL" mode="aspectFill"></image>
			
			<image class="coin" v-if="usertype == 1" src="../../static/ic_suggest.png" mode="aspectFill"></image>
		</view>
		<view class="segmented" v-if="usertype != 1">
			<uni-segmented-control class="segmented-control" :current="currentIndex" :values="items"
				:style-type="styleType" active-color="#006400" @clickItem="onClickItem" />
		</view>
		<view class="main">
			<view class="item" v-for="(item,index)  in dataList" :key="item._id" @click="itemClick(item,index)">
				<view class="item-content">
					<view class="bg">
						<image :src="item.bg" mode="aspectFill"></image>
						<view class="new" v-if="item.isNew">
							<image src="../../static/ic_new.png" mode="aspectFill"></image>
						</view>
					</view>
					<view class="text">
						{{item.name}}
					</view>
					<view class="score" @click="$emit('addScoreClick')" v-if="usertype != 1">
						<image class="coin" src="../../static/shouye/ic_coin.png" mode="aspectFill"></image>
						<view class="money">
							{{item.cost * -1}}
						</view>
					</view>
					
					<view class="item-lock" v-if="userInfo.score < item.minPlayScore">
						<image src="../../static/shouye/lock.png" mode="aspectFill"></image>
					</view>
				</view>
			</view>
		</view>
	</view>

	<view>
		<!-- 提示窗示例 -->
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog type="base" cancelText="取消" confirmText="观看广告修改一次" title="用户信息每个自然月只可以修改一次"
				@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref
	} from "vue"
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app"
	import {
		getUserOpenId
	} from "../../utils/getOpenId";
	import {
		onShareAppMessage,
		onShareTimeline
	} from "@dcloudio/uni-app";
	import {
		getTotalUserScore,
		getUserScoreFromCloud,
		saveUserTotalScoreToCloud,
		getUserScore,
		addUserScore,
		saveUserAddScoreToLocal,
		SignInGetScore,
		SignInGetScoreLocal,
		saveUserCloudScoreToLocal
	} from '../../store/scoreManager.js'
	import {
		md5
	} from 'js-md5';

	import {
		getTodayDateString,
		getTodayMonthString,
		kAppToken,
		kAppKey
	} from '../../utils/common.js'

	import CryptoJS from '../../utils/cryptojs.js'

	// const iv = CryptoJS.enc.Utf8.parse(kAppKey);
	const iv = CryptoJS.enc.Utf8.parse("");
	// 导入云对象
	const appManager = uniCloud.importObject('appManager');

	const alertDialog = ref(null);
	const score = ref(0);
	const level = ref(1);
	const dataList = ref([])
	const guaguaList = ref([])
	let userInfo = ref({})
	const db = uniCloud.database();
	let usertype = 1;
	let isfirst = false;
	// 若在开发者工具中无法预览广告，请切换开发者工具中的基础库版本
	// 在页面中定义激励视频广告
	let videoAd = null
	// 若在开发者工具中无法预览广告，请切换开发者工具中的基础库版本
	// 在页面中定义插屏广告
	let interstitialAd = null


	// 判断用户是否是新用户 时间点>3天
	let isNewUser = false
	const items = ref(['常规场', '5倍场', '10倍场'])
	const currentIndex = ref(0)
	// 0 签到积分  1 修改用户信息
	const adType = ref(0)
	
	const appKey = ref({})
	
	onLoad((e) => {
		// #ifdef MP
		// 在页面onLoad回调事件中创建激励视频广告实例
		if (wx.createRewardedVideoAd) {
			videoAd = wx.createRewardedVideoAd({
				adUnitId: 'adunit-b5c90278c107a744'
			})
			videoAd.onLoad(() => {})
			videoAd.onError((err) => {
				console.error('激励视频光告加载失败', err)
			})
			videoAd.onClose((res) => {
				// 用户点击了【关闭广告】按钮
				if (res && res.isEnded) {
					// 正常播放结束，可以下发游戏奖励
					console.log("观看完毕");
					if (adType.value == 0) {
						// SignInGetScore
						userInfo.value.score = saveUserAddScoreToLocal(1000, 1)
					} else if (adType.value == 1) {
						uni.navigateTo({
							url: '/pages/register/userinfo'
						})
					}
				} else {
					// 播放中途退出，不下发游戏奖励
					console.log("中途退出");
				}
			})
		}

		// 在页面onLoad回调事件中创建插屏广告实例
		if (wx.createInterstitialAd) {
			interstitialAd = wx.createInterstitialAd({
				adUnitId: 'adunit-1722f7e6276cc54a'
			})
			interstitialAd.onLoad(() => {})
			interstitialAd.onError((err) => {
				console.error('插屏广告加载失败', err)
			})
			interstitialAd.onClose(() => {})
		}
		// #endif

		usertype = uni.getStorageSync("userType");
		if (!usertype) {
			usertype = 1;
		}
		isfirst = true;

		appKey.value = uni.getStorageSync("appKey");

	})

	// segment点击
	function onClickItem(e) {
		currentIndex.value = e.currentIndex;
		if (guaguaList.value) {
			dataList.value = guaguaList.value.filter(obj => obj.multipeType == items.value[currentIndex.value])
		} else {
			getguaguaList(206)
		}
	}

	onShow(() => {
		if (usertype == 2) { // 正常模式
			userInfo.value.score = getTotalUserScore();
			getguaguaList(206)
			// 如果不是首次进入 其他页面返回
			if (isfirst) {

				// 首次进入 加载用户信息
				const openid = uni.getStorageSync("UserOpenId");
				// 导入云对象
				// 使用AES算法、CBC模式和PKCS#7填充对明文进行加密
				const encryptedData = CryptoJS.AES.encrypt(openid, kAppToken, {
					iv: iv, // 使用上面定义的IV
					mode: CryptoJS.mode.CBC, // 加密模式设置为CBC
					padding: CryptoJS.pad.Pkcs7, // 填充方式设置为PKCS#7
				}).toString();
				// 调用云对象方法
				appManager.getUserInfo({
					data: encryptedData
				}).then(res => {
					// const decryptedData = CryptoJS.AES.decrypt(res.data, kAppToken, {
					// 	iv: iv, // 使用上面定义的IV
					// 	mode: CryptoJS.mode.CBC, // 加密模式设置为CBC
					// 	padding: CryptoJS.pad.Pkcs7, // 填充方式设置为PKCS#7
					// }).toString(CryptoJS.enc.Utf8);
					// const body = JSON.parse(decryptedData);
					const user = res.data[0];
					console.log("getUserInfo: " + JSON.stringify(user));
					if (user && user.score) {
						saveUserCloudScoreToLocal(user.score);
						userInfo.value = user;
						if (!userInfo.value.avatar || userInfo.value.avatar == "") {
							userInfo.value.avatar = '../../static/logo.png'
						}
					}
					userInfo.value.score = getTotalUserScore();
					isfirst = false;
					// 判断用户是否是新用户
					const current = new Date().getTime();
					// 判断是否是新用户的小时数
					const isNewHour = uni.getStorageSync("isNewUser");
					if (!isNewHour) {
						isNewHour = 0;
					}
					if (current - userInfo.value.register_date < isNewHour * 60 * 60 * 1000) {
						isNewUser = true
						console.log("新用户");
					} else {
						console.log("老用户");
						isNewUser = false
					}
				}).catch(e => {

				});

			}
		} else { // 提审模式
			userInfo.value.score = getUserScore();
			getguaguaList(205);
		}
	})

	function getguaguaList(version) {
		if (guaguaList.value.length != 0) {
			if (version == 205) {
				dataList.value = guaguaList.value;
			} else {
				dataList.value = guaguaList.value.filter(obj => obj.multipeType == items.value[currentIndex.value])
			}
		} else {
			const param = {
				version: version
			};
			// 使用AES算法、CBC模式和PKCS#7填充对明文进行加密
			const encryptedData = CryptoJS.AES.encrypt(JSON.stringify(param), kAppToken, {
				iv: iv, // 使用上面定义的IV
				mode: CryptoJS.mode.CBC, // 加密模式设置为CBC
				padding: CryptoJS.pad.Pkcs7, // 填充方式设置为PKCS#7
			}).toString();

			appManager.getGameList({
				data: encryptedData
			}).then(res => {
				const decryptedData = CryptoJS.AES.decrypt(res.data, kAppToken, {
					iv: iv, // 使用上面定义的IV
					mode: CryptoJS.mode.CBC, // 加密模式设置为CBC
					padding: CryptoJS.pad.Pkcs7, // 填充方式设置为PKCS#7
				}).toString(CryptoJS.enc.Utf8);
				const body = JSON.parse(decryptedData);
				if (body && body.data) {
					// console.log("获取游戏列表body.data: " + JSON.stringify(body.data));
					if (version == 205) {
						if (body.data && body.data.length > 0) {
							dataList.value = body.data;
						}
					} else {
						if (body.data && body.data.length > 0) {
							guaguaList.value = body.data;
							dataList.value = guaguaList.value.filter(obj => obj.multipeType == items.value[
								currentIndex.value])
								
							items.value = [...new Set(guaguaList.value.map(obj => obj.multipeType))];
						}
					}
				}
			});
		}
	}



	function loadHomeAd() {
		const key = "shouyeADCount";
		const count = uni.getStorageSync(key);
		const day = getTodayDateString();
		if (count) {
			const c = count.split("--");
			if (c[0] == day) {
				if (Number(c[1]) < 3) {
					loadAD()
					uni.setStorageSync(key, day + "--" + (Number(c[1]) + 1))
				}
			} else {
				loadAD()
				uni.setStorageSync(key, day + "--" + 1)
			}
		} else {
			loadAD()
			uni.setStorageSync(key, day + "--" + 1)
		}
	}

	function loadAD() {
		// 在适合的场景显示插屏广告
		if (interstitialAd) {
			interstitialAd.show().catch((err) => {
				console.error('插屏广告显示失败', err)
			})
		}
	}

	// 用户头像点击
	function userInfoClick() {
		if (usertype === 2) {
			// 每个自然月只能修改一次
			const currentMonth = getTodayMonthString()
			if (userInfo.value.updateuserdate && userInfo.value.updateuserdate == currentMonth) {
				alertDialog.value.open()
			} else {
				uni.navigateTo({
					url: '/pages/register/userinfo'
				})
			}
		}
	}

	function suggestClick(e) {
		if(appKey.value.isJump && usertype !=1){
			uni.navigateToMiniProgram({
			    appId: appKey.value.miniappkey, // 填入目标小程序的 appId
			    path: appKey.value.path, // 打开的页面路径，如果为空则打开首页
			    extraData: {
			        // 需要传递给目标小程序的数据
			    },
			    success(res) {
			        // 打开成功的回调
			    },
			    fail(err) {
			        // 打开失败的回调
			    }
			});

		}else{
			uni.navigateTo({
				url: '/pages/index/suggest?' + 'usertype=' + usertype
			})
		}
		// uni.navigateTo({
		// 	url: '/pages/detail/detail6'
		// })
	}

	function dialogConfirm() {
		if (videoAd) {
			adType.value = 1;
			videoAd.show().catch(() => {
				// 失败重试
				videoAd.load()
					.then(() => videoAd.show())
					.catch(err => {
						console.error('激励视频 广告显示失败', err)
						uni.showToast({
							title: '广告拉取失败，请检查网络状况后重试',
							icon: "none",
							duration: 1500
						})
					})
			})
		}
	}

	function dialogClose() {
		alertDialog.value.close()
	}

	function rankClick() {
		uni.navigateTo({
			url: '/pages/index/rank?' + 'usertype=' + usertype
		})
	}

	// 添加积分
	function addScoreClick() {
		// 用户触发广告后，显示激励视频广告
		if (usertype === 2) {
			adType.value = 0
			// userInfo.value.score = SignInGetScore()
			if (videoAd) {
				videoAd.show().catch(() => {
					// 失败重试
					videoAd.load()
						.then(() => videoAd.show())
						.catch(err => {
							console.error('激励视频 广告显示失败', err)
							uni.showToast({
								title: '广告拉取失败，请检查网络状况后重试',
								icon: "none",
								duration: 1500
							})
						})
				})
			}
		} else {
			userInfo.value.score = SignInGetScoreLocal();
		}
	}

	async function itemClick(item, index) {
		if (usertype === 2) {
			if(userInfo.value.score < item.minPlayScore){
				uni.showToast({
					title: '积分必须达到$'+item.minPlayScore +"才能开启,您可以到低等级场/点击积分观看广告获取更多积分。",
					icon: "none",
					duration: 3000
				})
				return;
			}
			if (userInfo.value.score >= item.cost * -1) {
				// userInfo.value.score = saveUserAddScoreToLocal(item.cost);
				// console.log(item + index);
				const urlStr = '/pages/detail/detail' + (item.type) + '?itemDetail=' + JSON.stringify(item) +
					'&isNewUser=' + isNewUser;
				// const urlStr = '/pages/detail/details'+'?itemDetail=' + JSON.stringify(item);
				// url: `/pages/taskDetails/taskDetails?id=${id}`,
				uni.navigateTo({
					url: urlStr
				})
			} else {
				uni.showToast({
					title: '积分不够了',
					icon: "none",
					duration: 1500
				})
			}
		} else {
			// userInfo.value.score = addUserScore(-50);
			// if (userInfo.value.score >= 0) {
			// const urlStr = '/pages/detail/detail5';
			const urlStr = '/pages/detail/detail' + (item.type) + '?title=' + item.name + '&usertype=' + usertype +
				'&cost=' + item.cost + '&itemDetail=' + JSON.stringify(item);
			uni.navigateTo({
				url: urlStr
			})
			// }
		}
	}

	//分享给好友
	// onShareAppMessage((e) => {
	// 	return {
	// 		title: "喜乐刮刮卡",
	// 		path: "/pages/index/shouye"
	// 	}
	// })

	// //分享朋友圈
	// onShareTimeline(() => {
	// 	return {
	// 		title: "喜乐刮刮卡",
	// 		path: "/pages/index/shouye"
	// 	}
	// })
</script>

<style lang="scss">
	@font-face {
		font-family: NumFont;
		src: url('https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/font/HONORSans-Bold.ttf');
	}

	.segmented {
		position: relative;
		margin: auto;
		width: 90%;
		height: 70rpx;
		margin-top: 30rpx;
		background-color: transparent;
	}

	.main {
		position: relative;
		width: 100%;
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		row-gap: 50rpx;
		column-gap: 50rpx;

		padding: 0rpx 50rpx 50rpx 50rpx;

		.item {
			width: 300rpx;
			height: 450rpx;
			margin-top: 20rpx;
			position: relative;
			.item-lock{
				width: 100%;
				height: 100%;
				position: absolute;
				top: 0rpx;
				left: 0rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: rgba(0, 0, 0, 0.3);
				image{
					width: 100rpx;
					height: 100rpx;
				}
			}
			.item-content{
				width: 100%;
				height: 100%;
				position: relative;
				.bg {
					left: 0rpx;
					top: 0rpx;
				
					image {
						border-radius: 20rpx;
						width: 100%;
						height: 100%;
					}
				
					.new {
						position: absolute;
						left: 0rpx;
						top: 0rpx;
						border-radius: 10rpx;
						width: 100rpx;
						height: 100rpx;
				
						image {
							width: 100%;
							height: 100%;
						}
					}
				}
				
				.text {
					position: absolute;
					text-align: center;
					width: 100%;
					top: 200rpx;
					left: 0;
					color: white;
					font-family: 'NumFont';
					font-size: 60rpx;
					background-color: rgba(0, 0, 0, 0.5);
					font-weight: bold;
				}
				
				.score {
					position: absolute;
					top: 10rpx;
					right: 10rpx;
					height: 60rpx;
					width: 180rpx;
					align-items: center;
					display: flex;
					flex-direction: row;
					font-size: 20px;
					font-weight: 500;
					margin-left: 30rpx;
					padding: 5rpx 10rpx;
					border-radius: 45rpx;
					background-color: rgba(0, 0, 0, 0.5);
				
					.coin {
						height: 50rpx;
						width: 50rpx;
					}
				
					.money {
						color: white;
						text-align: center;
						margin: auto;
					}
				}
			}
		}
	}

	.header {
		position: relative;
		top: 0;
		left: 0;
		width: 100%;
		height: 166rpx;
		background-color: transparent;
		/* background-color: black; */
		display: flex;
		flex-direction: row;
		align-items: bottom;

		.level {
			bottom: 10rpx;
			height: 60rpx;
			color: black;
		}

	}

	.content {
		position: absolute;
		width: 100%;
		height: 100%;

		/* background-image: url("/static/bg.png");
		background-size: cover; */
	}



	.bg {
		position: absolute;
		width: 100%;
		height: 100%;
	}

	.suggest {
		z-index: 1000;
		position: fixed;
		bottom: 100rpx;
		right: 50rpx;
		width: 100rpx;
		height: 100rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}
</style>